package com.keelau.crawler;


import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.keelau.crawler.model.AliProductDetail;
import com.keelau.idao.model.AliProductPrice;
import com.keelau.crawler.model.AliSKUDetail;
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.JSValue;
import com.teamdev.jxbrowser.chromium.dom.By;
import com.teamdev.jxbrowser.chromium.dom.DOMDocument;
import com.teamdev.jxbrowser.chromium.dom.DOMElement;
import com.teamdev.jxbrowser.chromium.events.FinishLoadingEvent;
import com.teamdev.jxbrowser.chromium.events.LoadAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Named;
import java.io.IOException;
import java.util.*;

@Named("crawler")
public class AliProCrawler {

    private String url;

    private DOMDocument domDocument;

    private Browser browser;

    private AliProductDetail aliProductDetail;

    public  LoadAdapter loadAdapter;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    public void setUrl(String url) {
        this.url = url;
    }

    public void setDomDocument(DOMDocument domDocument) {
        this.domDocument = domDocument;
    }

    public void setBrowser(Browser browser) {
        this.browser = browser;
    }

    public Browser getBrowser() {
        return browser;
    }



    public String getUrl() {
        return url;
    }

    public AliProductDetail getAliProductDetail() {
        return aliProductDetail;
    }

    public DOMDocument getDomDocument() {
        return domDocument;
    }

    public AliProCrawler(String url){

    }

    public  AliProCrawler(){}

    public  AliProCrawler(DOMDocument domDocument){

    }

    public String abc = "abc";

    public void testAutoWrite(){
        System.out.println("auto write success.");
    }

    public void loadUrl(){
        if(browser==null)
            browser = new Browser();

        if(loadAdapter!=null)
            browser.addLoadListener(loadAdapter);
        else{
            browser.addLoadListener(new LoadAdapter() {
                @Override
                public void onFinishLoadingFrame(FinishLoadingEvent event) {
                    super.onFinishLoadingFrame(event);
                    getAliProductDetail();
                }
            });
        }
        browser.loadURL(url);
    }

    public AliProductDetail getProductDetail() throws IOException {
        JSValue iDetailData = browser.executeJavaScriptAndReturnValue(
                "window.iDetailData");
        if(iDetailData.isObject()) {
            //logger.info("iDetailData:" + iDetailData.asObject().toJSONString());
            JSValue sku = iDetailData.asObject().getProperty("sku");
            String skuJsonStr = sku.asObject().toJSONString();
            String skuDetailJson = sku.asObject().getProperty("skuMap").asObject().toJSONString();
            ObjectMapper mapper = new ObjectMapper();

            aliProductDetail = mapper.readValue(skuJsonStr, AliProductDetail.class);
            aliProductDetail.skuDetails = getSKUDetail(skuDetailJson);

            return aliProductDetail;
        }
        return null;
    }

    public ArrayList<AliSKUDetail> getSKUDetail(String skuDetailStr) throws IOException {
        ArrayList<AliSKUDetail> aliSKUDetails = new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();
        Map<String,AliSKUDetail> map =mapper.readValue(skuDetailStr,new TypeReference<Map<String, AliSKUDetail>>(){

        });
        Set<Map.Entry<String,AliSKUDetail>> set = map.entrySet();
        for (Map.Entry<String,AliSKUDetail> e:set
                ) {
            //System.out.println("entry-key"+e.getKey());
            //System.out.println("entry-sku"+ e.getValue().skuId);
            AliSKUDetail detail = e.getValue();
            detail.propValue = e.getKey();
            aliSKUDetails.add(detail);
        }
        return  aliSKUDetails;
    }

    public AliProductPrice getAliProductPrice(){
        browser = new Browser();
        AliProductPrice price = new AliProductPrice();
        DOMElement priceModel = domDocument.findElement(By.id("mod-detail-price"));
        DOMElement priceTitleTr = priceModel.findElement(By.xpath("//tr[@class='price']"));
        DOMElement priceTitleTD = priceTitleTr.findElement(By.cssSelector("price-title"));

        String ladderClass = priceTitleTD.getAttribute("class").split(" ")[1];

        int ladderCount = Integer.parseInt( ladderClass.split("-")[1]);
        return  price;
    }

    public void dispose(){
        if(!browser.isDisposed()){
            browser.dispose();
        }
    }
}
